package com.campus.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.app.mapper.RoleMapper;
import com.campus.app.mapper.UserMapper;
import com.campus.commons.entity.Role;
import com.campus.commons.entity.Teacher;
import com.campus.app.mapper.TeacherMapper;
import com.campus.app.service.TeachersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.commons.entity.User;
import com.campus.commons.utils.Error;
import com.campus.commons.utils.MyPage;
import com.campus.commons.utils.Result;
import com.campus.config.lifecycle.CustomInit;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

/**
 * <p>
 * 老师表 服务实现类
 * </p>
 *
 * @author Rin
 * @since 2020-12-24
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeachersService {
    @Autowired

    private CustomInit customInit;
    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public Teacher getTeacherByUserId(Integer userId) {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        return teacherMapper.selectOne(queryWrapper);
    }

    @Override
    public Result<List<Teacher>> getTeachers(Teacher teacher) {
        return null;
    }

    @Override
    public Result<List<Teacher>> getTeachers(MyPage<Teacher> myPage) {

        return null;
    }

    @Override
    public Result<List<Teacher>> getTeachersByRoleId(Integer roleId) {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("userId", "select id from user  where roleId="+roleId);
        return Result.result(teacherMapper.selectList(queryWrapper));
    }

    @Override
    public Result<List<Teacher>> getTeacherAll(int page, int limit) {
        Result<List<Teacher>> listResult = new Result<>();
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        Integer count = teacherMapper.selectCount(queryWrapper);
        List<Teacher> teachers = teacherMapper.getTeacherAll_xml((page - 1) * limit, limit);
        listResult.setSuccess(true);
        listResult.setTotal(count);
        listResult.setData(teachers);
        return listResult;
    }

    @Override
    public Result<List<Teacher>> getAllBy_xml(int page, int limit, String teacherName, String phone, String roleName, String idCard) {
        Result<List<Teacher>> result = new Result<>();
        List<Teacher> data = teacherMapper.getTeacherBy_xml((page - 1) * limit, limit, teacherName, phone, roleName, idCard);
        int count = 0;
        if (data.size() != 0) {
            count = teacherMapper.getTeacherBy_xmlCount(teacherName, phone, roleName, idCard);
        }
        result.setSuccess(true);
        result.setTotal(count);
        result.setData(data);
        return result;
    }

    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private UserMapper userMapper;
    @Override
    public Result delUser(int id, int userId) {

        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionTemplate);
        try {
            int count = teacherMapper.deleteById(id);
            count += userMapper.deleteById(userId);
            if (count != 2) {

                platformTransactionManager.rollback(transaction);
                return Result.error(Error.System, "事务回滚");
            }
        } catch (TransactionException e) {
            platformTransactionManager.rollback(transaction);
            return Result.error(Error.System, "事务回滚:" + e.getMessage());
        }
        customInit.setTeacher();

        platformTransactionManager.commit(transaction);
        return Result.success(true);
    }

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Result update(User user, Teacher teacher) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleName", teacher.getRoleName());
        Role role = roleMapper.selectOne(queryWrapper);
        user.setRoleid(role.getId());
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionTemplate);
        user.setId(teacher.getUserid());
        try {
            int count = userMapper.updateById(user);
            count += teacherMapper.updateById(teacher);
            if (count != 2) {
                platformTransactionManager.rollback(transaction);
                return Result.error(Error.System, "事务回滚");
            }
        } catch (TransactionException e) {
            platformTransactionManager.rollback(transaction);
            return Result.error(Error.System, "事务回滚：" + e.getMessage());
        }
        customInit.setTeacher();

        platformTransactionManager.commit(transaction);
        return Result.success(true);
    }

    @Override
    public Result addTeacher(User user, Teacher teacher) {
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionTemplate);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("id", "select id from role where roleName='" + teacher.getRoleName() + "' ");

        Role role = roleMapper.selectOne(queryWrapper);
        user.setRoleid(role.getId());
        try {
            int id = userMapper.insert(user);
            if (id != 1||user.getId()==0) {
                platformTransactionManager.rollback(transaction);
                return Result.error(Error.System, "user插入失败事务回滚");
            }
            teacher.setUserid(user.getId());
            int teacherId = teacherMapper.insert(teacher);
            if (teacherId != 1) {
                platformTransactionManager.rollback(transaction);
                return Result.error(Error.System, "teacher插入失败事务回滚");
            }
        } catch (TransactionException e) {
            return Result.error(Error.Other_E1R, "发生异常事务回滚：" + e.getMessage());
        }
        customInit.setTeacher();
        platformTransactionManager.commit(transaction);
        return Result.success(true);
    }

    @Override
    public Boolean checkIdCard(String idcard) {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("idCard", idcard);
        Integer count = teacherMapper.selectCount(queryWrapper);
        return count == 1;
    }


}
